extends CharacterBody2D

@onready var navigation_agent = $NavigationAgent2D
# 怪物属性
@export var max_health: int = 100
@export var attack_damage: int = 10
@export var move_speed: float = 50.0
@export var attack_cooldown: float = 1.0
@export var detection_range: float = 1800.0  # 检测玩家的范围
@export var target_reached_distance: float = 30.0  # 到达目标的判定距离
@export var path_update_interval: float = 0.5  # 路径更新频率（秒）
@export var avoid_distance: float = 20.0  # 与其他怪物保持的距离
# 状态变量
var current_health: int
var current_target: Node2D = null
var attack_timer: float = 0.0
var is_blocked: bool = false
var last_path_update: float = 0.0
# 缓存玩家组
var roles: Array = []

func _ready():
	 # 配置导航代理
	navigation_agent.target_desired_distance = target_reached_distance
	
	current_health = max_health
	# 将自己添加到怪物组，用于被其他怪物检测
	add_to_group("mods")
	# 初始化玩家组
	roles = get_tree().get_nodes_in_group("roles")
	# 设置物理层和掩码，确保与其他怪物碰撞
	set_collision_layer_value(2, true)  # 假设层2是怪物层
	set_collision_mask_value(2, true)   # 与其他怪物碰撞

	

func _physics_process(delta):
	last_path_update += delta
	 # 寻找玩家目标
	if last_path_update >= path_update_interval:
		find_target()
		if current_target:
			navigation_agent.target_position = current_target.global_position
		last_path_update = 0.0
	# 沿导航路径移动
	move_along_path(delta)

func find_target():
	var players = get_tree().get_nodes_in_group("roles")
	if players.size() == 0:
		current_target = null
		return
	
	var closest_player = null
	var closest_distance = INF
	for player in players:
		if player.is_queued_for_deletion():
			continue
		
		var distance = global_position.distance_to(player.global_position)
		# 只检测范围内的玩家
		if distance < detection_range and distance < closest_distance:
			closest_distance = distance
			closest_player = player
	
	current_target = closest_player
		

func take_damage(damage: int):
	current_health -= damage
	if current_health <= 0:
		die()

func die():
	remove_from_group("mods")
	add_to_group("dead")
	queue_free()

func check_blocked_state():
	# 检查是否与其他怪物碰撞
	
	is_blocked = false
	for i in range(get_slide_collision_count()):
		var collision = get_slide_collision(i)
		if collision.get_collider().is_in_group("mods"):
			is_blocked = true
			break    
			
# 沿导航代理计算的路径移动
func move_along_path(delta):
	var direction =Vector2.ZERO
		 # 检测是否有其他怪物在前方
	var avoid_dir = check_and_avoid_monsters()
	 # 融合方向：优先沿导航路径，必要时避让
	if avoid_dir.length() > 0:
		direction = avoid_dir
	else:
		# 如果没有目标或已到达目标，停止移动
		if not current_target or navigation_agent.is_target_reached():
			velocity = Vector2.ZERO
			return
		
		# 获取下一个路径点
		var next_point = navigation_agent.get_next_path_position()
		# 计算到下一个路径点的方向
		direction = (next_point - self.global_position).normalized()
		
	# 移动到目标
	velocity = direction * move_speed
	move_and_slide()

# 当目标位置变化时（可选）
# 检测附近的怪物并计算避让方向
func check_and_avoid_monsters() -> Vector2:
	var avoid_dir = Vector2.ZERO
	for monster in get_tree().get_nodes_in_group("mods"):
		if monster == self:
			continue
		# 只处理过近的怪物
		var dist = global_position.distance_to(monster.global_position)
		if dist < avoid_distance:
			# 远离该怪物的方向
			avoid_dir = (global_position - monster.global_position).normalized()

	return avoid_dir
